package libraries.basis.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

/**
 * 【Android】不弹root请求框检测手机是否root
 1.https://www.cnblogs.com/waylife/p/android_root_check.html

 android中Root权限的判断与获取
 2.https://blog.csdn.net/wojiaochencanmao/article/details/52209395
 */
public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = MainActivity.class.getName();
    TextView tv_result;
    StringBuilder resultSb = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        tv_result = findViewById(R.id.tv_result);


        isSuFileExist();
        isLinuxCmdExecutable();
        execRootCommand();

        tv_result.setText(resultSb.toString());
    }

    /**
     * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
     * 命令： String apkRoot="chmod 777 "+getPackageCodePath();
     * RootCommand(apkRoot);
     * @return 应用程序是/否获取Root权限
     */
    public boolean execRootCommand() {
        String command = "chmod 777 " + getPackageCodePath();
        Process process = null;
        DataOutputStream os = null;

        try {

            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();

        } catch (Exception e) {
            Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
            resultSb.append("\n\nexec ").append(command)
                    .append("\nRoot Err: ").append(e.getMessage());
            return false;

        } finally {

            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }

        resultSb.append("\n\nexec ").append(command)
                .append(" Root SUC");

        return true;

    }

    /** 判断手机是否root，不弹出root请求框<br/> */
    public boolean isLinuxCmdExecutable() {
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";
        boolean result = false;
        if (new File(binPath).exists() && isExecutable(binPath)) {
            resultSb.append("\n\nisLinuxCmdExecutable /system/bin/su true");
            result = true;
        }
        if (new File(xBinPath).exists() && isExecutable(xBinPath)) {
            resultSb.append("\n\nisLinuxCmdExecutable /system/xbin/su true");
            result = true;
        }

        if (result){
            return true;
        }

        resultSb.append("\n\nisLinuxCmdExecutable false");

        return false;
    }

    /**
     * 是否可以在指定目录下面执行linux命令
     * @param filePath
     * @return
     */
    private boolean isExecutable(String filePath) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("ls -l " + filePath);
            // 获取返回内容
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String str = in.readLine();
            Log.i(LOG_TAG, str);
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x')
                    return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(p!=null){
                p.destroy();
            }
        }
        return false;
    }

    public boolean isSuFileExist() {
        boolean root = false;
        try {
            if ((!new File("/system/bin/su").exists())
                    && (!new File("/system/xbin/su").exists())) {
                resultSb.append("isSuFileExist true");
                root = false;
            } else {
                resultSb.append("isSuFileExist false");
                root = true;
            }

        } catch (Exception e) {
        }

        return root;
    }
}
